package com.fanrenqiji.modules.sys.web;

import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.persistence.Page;
import com.fanrenqiji.common.web.BaseController;
import com.fanrenqiji.modules.sys.entity.Config;
import com.fanrenqiji.modules.sys.service.ConfigService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lijian E-mail:ljz0721cx@163.com
 * @version 创建时间：2015年2月28日 下午2:41:02
 * @description 品牌管理的视图交互
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/config")
public class ConfigController extends BaseController {

	@Autowired
	private ConfigService configService;

	@ModelAttribute("config")
	public Config get(@RequestParam(required = false) Long id) {
		if (id != null) {
			return configService.getConfig(id);
		} else {
			return new Config();
		}
	}

	/**
	 * 在有model时候加载资源 获得权限列表
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:config:view")
	@RequestMapping(value = { "list", "" })
	public String list(Config config, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		Page<Config> configPage = configService.findConfigByPage(new Page<Config>(
				request, response), config);
		model.addAttribute("page", configPage);
		return "modules/sys/configList";
	}

	/**
	 * 用户添加更新配置表
	 * 
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:config:view")
	@RequestMapping(value = "form")
	public String form(Model model, Config config) {
		model.addAttribute("config", config);
		return "modules/sys/configForm";
	}
	
	
	/**
	 * 添加或更新配置信息
	 * 
	 * @param config
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("sys:config:edit")
	@RequestMapping(value = "save")
	public String save(Config config, Model model,
			RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, config)) {
			return form(model, config);
		}
		configService.save(config);
		addMessage(redirectAttributes, "保存配置信息成功");
		return "redirect:" + GlobalSetting.getAdminPath()
				+ "/sys/config/?repage&id=" + config.getId();
	}


	/**
	 * 删除操作配置信息
	 * 
	 * @return
	 */
	@RequestMapping("delete")
	@RequiresPermissions("sys:config:edit")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		configService.delete(id);
		addMessage(redirectAttributes, "配置信息删除成功");
		return "redirect:" + GlobalSetting.getAdminPath() + "/sys/config/";
	}
}
